import { H3, HTTPError, onError } from "h3";
import indexRoute from "./routes/index.ts";
import requestLogger from "./middleware/request_logger.ts";
import appSingature from "./middleware/signature.ts";
import rateLimit from "./middleware/rate_limit.ts";
import { logger, init as initLogger } from "./helper/logger.ts";

const app = new H3();
const APPID = "taRmG_p978HpF2lo3dXi";
const SECRET = "oXw9mV__B-dGnAzqjD3ykG-LD53MSC6m";

initLogger({
  production: process.env.NODE_ENV === "production",
  name: "trading-account",
});

// 请求日志记录, 生产环境建议使用 nginx 或 caddy 的日志
if (process.env.NODE_ENV !== "production") {
  app.use(requestLogger(logger.child({ name: "request-logger" })));
}

app.use(
  appSingature({
    getSecretkeyByAppid: async (appid) => {
      return APPID === appid ? SECRET : "";
    },
    prefix: "/stock_monitor/api",
    ignoredPaths: ["/system-monitor", "/trade_push"],
  }),
); // 应用签名
app.use(rateLimit()); // 限流

app.mount("/stock_monitor/api", indexRoute);

app.use(
  onError((error) => {
    const cause = error.cause as any;
    const isOriError = cause instanceof Error;
    logger.error(isOriError ? cause.stack : cause.data);
    throw HTTPError.status(
      error.status || 500,
      error.statusText || "Internal Server Error",
      {
        message: cause.message,
        cause: cause,
        data: isOriError ? undefined : cause.data,
      },
    );
  }),
);

export default app;
